package pkg

import (
	"api/basic/config"
	"context"
	"github.com/qiniu/go-sdk/v7/storagev2/credentials"
	"github.com/qiniu/go-sdk/v7/storagev2/http_client"
	"github.com/qiniu/go-sdk/v7/storagev2/uploader"
	"mime/multipart"
)

func Upload(file *multipart.FileHeader) (string, error) {

	yun := config.Config.QiNiu

	accessKey := yun.AccessKey
	secretKey := yun.SecretKey
	mac := credentials.NewCredentials(accessKey, secretKey)

	bucket := yun.Bucket
	key := file.Filename

	uploadManager := uploader.NewUploadManager(&uploader.UploadManagerOptions{
		Options: http_client.Options{
			Credentials: mac,
		},
	})

	open, err := file.Open()
	if err != nil {
		return "", err
	}

	defer open.Close()

	err = uploadManager.UploadReader(context.Background(), open, &uploader.ObjectOptions{
		BucketName: bucket,
		ObjectName: &key,
		CustomVars: map[string]string{
			"name": "github logo",
		},
		FileName: key,
	}, nil)

	return yun.Url + key, nil
}
